package cn.myspringboot.user.service.Impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.myspringboot.system.mapper.LogininfoMapper;
import cn.myspringboot.user.domain.Logininfo;
import cn.myspringboot.user.domain.User;
import cn.myspringboot.user.mapper.UserMapper;
import cn.myspringboot.user.query.UserQuery;
import cn.myspringboot.user.service.UserService;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    @Transactional
    public void add(User user) {
        if(StringUtil.isEmpty(user.getUserName())){
            throw new RuntimeException("用户名不能为空");
        }
        if(StringUtil.isEmpty(user.getPassword())){
            throw new RuntimeException("密码不能为空");
        }
        if(StringUtil.isEmpty(user.getPhone())){
            throw new RuntimeException("电话号码不能为空");
        }
        //生成盐值
        String salt = RandomUtil.randomString(32);
        user.setSalt(salt);
        //对密码进行加密 且不可以解密
        String pw = SecureUtil.md5(user.getPassword());
        user.setPassword(pw);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setDisable(1);
        logininfo.setType(1);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    @Override
    @Transactional
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        userMapper.batchDelete(ids);
    }

    @Override
    @Transactional
    public List<User> getUserByPage(UserQuery query) {
        return userMapper.getUserByPage(query);
    }
}
